package com.shigu.admin.manager.actions;

import com.alibaba.fastjson.JSON;
import com.opentae.data.mall.beans.ManagerRole;
import com.opentae.data.mall.beans.RolePermission;
import com.shigu.admin.manager.bo.AddRoleBO;
import com.shigu.admin.manager.bo.ChangePermissionBO;
import com.shigu.admin.manager.bo.PageSearchBO;
import com.shigu.admin.manager.common.CustomPager;
import com.shigu.admin.manager.common.JSONResult;
import com.shigu.admin.manager.services.AdminPermissionService;
import com.shigu.admin.manager.services.AdminRoleService;
import com.shigu.admin.manager.vo.RoleVO;
import com.shigu.admin.manager.vo.ZTreeVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 角色管理
 * Created by zhaohongbo on 16/5/13.
 */
@Controller
public class AdminRoleAction extends BaseAction {

    @Autowired
    AdminRoleService adminRoleService;

    @Autowired
    AdminPermissionService adminPermissionService;

    /**
     * 角色列表
     *
     * @return
     */
    @RequestMapping("rolelist")
    @RequiresPermissions("role:list")
    public String list(PageSearchBO bo, Model model) {
        if (bo.getPageNo() == null) {
            bo.setPageNo(1);
        }
        model.addAttribute("keyword", bo.getKeyword());
        model.addAttribute("pageNo", bo.getPageNo());
        CustomPager<RoleVO> pager = adminRoleService.selRoles(bo.getKeyword(), bo.getPageNo(), PageSearchBO.pageSize, null);
        model.addAttribute("pager", pager);
        return "sys/role";
    }

    /**
     * 添加角色
     *
     * @return
     */
    @RequestMapping("addrole")
    @RequiresPermissions("role:add")
    public String add(AddRoleBO bo, Model model) {
        String targetView = "sys/addrole";
        String result = "";
        if (bo.getSubmit() == null) {
            return targetView;
        }
        if ((bo.getRoleName() == null || "".equals(bo.getRoleName())) && bo.getSubmit() == 1) {
            result = "roleName";
            model.addAttribute("result", result);
            return targetView;
        }
        if ((bo.getRoleComment() == null || "".equals(bo.getRoleComment())) && bo.getSubmit() == 1) {
            result = "roleComment";
            model.addAttribute("result", result);
            return targetView;
        }
        String msg = null;
        ManagerRole mp = adminRoleService.checkRoleNameAndTag(bo.getRoleName(), bo.getRoleTag());
        if (mp == null) {//可以用
            Long pid = adminRoleService.addRole(bo.getRoleName(), bo.getRoleTag(), bo.getRoleComment());
            msg = "添加成功,pid:" + pid;
            bo.setRoleName(null);
            bo.setRoleComment(null);
            model.addAttribute("msg", msg);
            return targetView;
        } else {
            result = "tag";
            msg = "权限标签已经被使用";
            model.addAttribute("result", result);
            model.addAttribute("msg", msg);
            return targetView;
        }
    }

    /**
     * 修改用户状态
     *
     * @return
     */
    @RequestMapping("cgrole")
    @ResponseBody
    public JSONResult cgrole(Long pid) {
        if (pid == null) {
            return JSONResult.error();
        }
        int result = adminRoleService.changeRoleStatus(pid);
        if (result == 0) {
            obj = JSONResult.error();
        } else {
            obj = JSONResult.success();
        }
        return obj;
    }

    @RequestMapping("cprole")
    @RequiresPermissions("role:modify")
    public String changePermission3(ChangePermissionBO bo, Model model) {
        if (bo.getPageNo() == null) {
            bo.setPageNo(1);
        }
        CustomPager<RoleVO> pager = adminRoleService.selRoles(bo.getKeyword(), bo.getPageNo(), PageSearchBO.pageSize, 1);
        model.addAttribute("pager", pager);
        model.addAttribute("uid", bo.getUid());
        model.addAttribute("keyword", bo.getKeyword());
        model.addAttribute("pageNo", bo.getPageNo());
        List<ZTreeVO> trees = adminPermissionService.selAllPermissionFortreeByParentId(null);

        //查相关的权限
        List<RolePermission> rolePermissions = null;
        if (bo.getUid() != null) {
            rolePermissions = adminRoleService.selPermissionByRoleId(bo.getUid());
            checkNode(trees, rolePermissions);
            model.addAttribute("hastreeJsonstr", JSON.toJSONString(getZtreeVo(rolePermissions)));
        } else {
            model.addAttribute("hastreeJsonstr", "[]");
        }
        model.addAttribute("treeJsonstr", JSON.toJSONString(trees));
//        model.addAttribute("rolePermissions",rolePermissions);
        return "sys/changerole3";
    }

    private void checkNode(List<ZTreeVO> trees, List<RolePermission> permissions) {
        for (RolePermission rp : permissions) {
            ZTreeVO ztv = new ZTreeVO();
            ztv.setId(rp.getPermissionId());
            int index = trees.indexOf(ztv);
            if (index >= 0) {
                trees.get(index).setChecked(true);
            }
        }
    }

    /**
     * 返回子节点的子节点
     *
     * @param pid
     * @return
     */
    @RequestMapping("rolesubPermission")
    @ResponseBody
    public List<ZTreeVO> synSubPermission(Long uid, Long pid) {
        if (pid == null) {
            return Collections.emptyList();
        }
        List<ZTreeVO> trees = adminPermissionService.selAllPermissionFortreeByParentId(pid);
        if (uid != null) {
            if (trees.size() > 0) {
                String ids = StringUtils.join(trees, ",");
                List<RolePermission> rolePermissions = adminRoleService.selPermissionByRoleIdAndPids(uid, ids);
                checkNode(trees, rolePermissions);
            }
        }
        return trees;
    }

    /**
     * 我拥有的权限
     *
     * @param uid
     * @return
     */
    @RequestMapping("rolehasPermission")
    @ResponseBody
    public List<ZTreeVO> hasSubPermission(Long uid) {
        if (uid == null) {
            return Collections.emptyList();
        }
        return getZtreeVo(adminRoleService.selPermissionByRoleId(uid));
    }

    private List<ZTreeVO> getZtreeVo(List<RolePermission> permissions) {
        List<ZTreeVO> ztlist = new ArrayList<ZTreeVO>();
        for (RolePermission rp : permissions) {
            ZTreeVO zt = new ZTreeVO();
            zt.setChecked(true);
            zt.setId(rp.getPermissionId());
            zt.setpId(rp.getParentPid());
            zt.setName(rp.getPermissionComment() + " (" + rp.getPermissionTag() + ")");
            zt.setOpen(true);
            zt.setTag(rp.getPermissionTag());
            zt.setTagComment(rp.getPermissionComment());
            ztlist.add(zt);
        }
        return ztlist;
    }

    /**
     * 修改关系,新的多返回一个已选的
     *
     * @return
     */
    @RequestMapping("obpermission")
    @ResponseBody
    public JSONResult obpermission2(Long pid, Long uid) {
        if (uid == null || pid == null) {
            obj = JSONResult.error("参数有误");
            return obj;
        }
        adminRoleService.changeRelation(uid, pid);
        obj = JSONResult.success("", hasSubPermission(uid));
        return obj;
    }
}
